Ext.namespace("Milan.widget");
Milan.widget.Selector = Class.create();
Milan.widget.Selector.prototype = 
{
	/**
	 * 构造函数
	 * @param {Object} config
	 *         config为一个Object
	 *         config.orgType   : 用于标识该控件的类型
	 *         config.title 		 : 用于标识选择控件的类型
	 *         config.deptUrl 		 : 用于构建选择器重的部门树
	 *         config.quickSelectUrl : 用于构建最近选择的十条记录
	 *         config.searchUrl 	 : 用于执行搜索操作
	 *         config.supportCheckAll: 是否支持全选
	 *         config.isRecentEnable : 最近使用是否可用
	 *         config.isUpdateRecentEnable : 是否更新最近使用
	 *         config.isDeptSelEnable : 是否启用部门选择列表
	 *         config.isSearchEnable : 是否启用搜索框
	 *         config.pageSize : 分页每页数量
	 * @param {Object} isMulti
	 * @param {Object} callBackConfig
	 *         callBackConfig为一个Object，其中包含4个参数
	 *         callBackConfig.itemCheckCallBack  ：点击选项后执行回调
	 *         callBackConfig.beforeListShowCallBack : 列表渲染完毕前的回调
	 *         callBackConfig.onListShowCallBack : 列表渲染完毕后的回调
	 *         callBackConfig.onSelectedCallBack : 选择完毕后的回调
	 *         callBackConfig.onCancelCallBack   : 取消选择的回调
	 */
	initialize : function(config,isMulti,callBackConfig)
	{
		this.orgSelectorLoaded = false;
		this.onlineUserLoaded = false;
		/**
		 * 检查必须的参数是否已经都设置好
		 */
		if(config)
		{
			if(!config.orgType) alert("config.orgType does not exist!");
			if(!config.title) alert("config.title does not exist!");
			if(!config.deptUrl) 
				alert("config.deptUrl does not exist!");
			else
				config.deptUrl = encodeURI(config.deptUrl);
			if(!config.quickSelectUrl)
				alert("config.quickSelectUrl does not exist!");
			else
				config.quickSelectUrl = encodeURI(config.quickSelectUrl+"&historyType="+config.orgType);
			if(!config.searchUrl) 
				alert("config.searchUrl does not exist!");
			else
				config.searchUrl = encodeURI(config.searchUrl);
			
			//全部标签的title,如果有没有传入,则根据title来区分人员、部门、岗位并创建标签title
			if(!config.orgTitle){
				if(config.title.indexOf("人")>-1||config.title.indexOf("用户")>-1){
					config.orgTitle = "所有用户";
				}else{
					config.orgTitle=config.title;
				}
			}
		}
		else
		{
			alert("config not exist!");
		}
		if(!config.isUpdateRecentEnable) config.isUpdateRecentEnable = true;
		if(config.supportCheckAll==undefined) config.supportCheckAll = true;
		if(config.isRecentEnable==undefined) config.isRecentEnable = true;
		if(config.isDeptSelEnable==undefined) config.isDeptSelEnable = true;
		if(config.isSearchEnable==undefined) config.isSearchEnable = true;
		if(!config.isContainChildren) config.isContainChildren = false;
		if(!config.isOnlineUser) config.isOnlineUser = false;
		if(!config.height)config.height=380;
		if(!config.columnModel)
		{
			if(config.orgType == '12'){
				//设置名称宽度
				config.columnModel={
					columns : [{
						header : "<div id ='orgSelect-listCnt-header'></div>",
						dataIndex : "id",
						style:"padding-left: 1px;width:15px;"
					},
					{
						header : "名称",
						dataIndex : "name",
						style:"width:160pt"
					},
					{
						header : "部门",
						dataIndex : "orgInfo"
					}
					]
				};
				//设置分页
				if(!config.pageSize){
					config.pageSize = 30;
				}
			}if(config.orgType == '13'){
				//设置名称宽度
				config.columnModel={
					columns : [{
						header : "<div id ='orgSelect-listCnt-header'></div>",
						dataIndex : "id",
						style:"padding-left: 1px;width:15px;"
					},
					{
						header : "名称",
						dataIndex : "name",
						style:"width:160pt"
					},
					{
						header : "-",
						dataIndex : "orgInfo"
					}
					]
				};
				//设置分页
				if(!config.pageSize){
					config.pageSize = 30;
				}
			}else{
				config.columnModel={
					columns : [{
						header : "<div id ='orgSelect-listCnt-header'></div>",
						dataIndex : "id",
						style:"padding-left: 1px;width:15px;"
					},
					{
						header : "名称",
						dataIndex : "name"
					},
					{
						header : "部门",
						dataIndex : "orgInfo"
					}
					]
				};
			}
		}
		
		this.config = config;
		this.callBackConfig = callBackConfig;
		this.isMulti = isMulti;
		this.createUI();
		//this.container.bgDiv.style.height= document.body.scrollHeight;
		//this.initOrgSelector();
		//this.initItemList();
	},
	
	_insertElement : function(srcNode,where,parsedNode)
	{
        switch(where){
            case "beforeBegin":
                srcNode.parentNode.insertBefore(parsedNode,srcNode);
                break;
            case "afterBegin":
                srcNode.insertBefore(parsedNode,srcNode.firstChild);
                break;
            case "beforeEnd":
                srcNode.appendChild(parsedNode);
                break;
            case "afterEnd":
                if(srcNode.nextSibling)
                    srcNode.parentNode.insertBefore(parsedNode,srcNode.nextSibling);
                else
                    srcNode.parentNode.appendChild(parsedNode);
                break;
            }
       } 
	,
	createUI : function()
	{
		var selectorCnt = Milan.widget._createEle("DIV");
		selectorCnt.style.height=this.config.height+"px";
		this.createnCnt();
		this._insertElement(this.container.body,"afterBegin",selectorCnt);
		//this.container.body.insertAdjacentElement("afterBegin",selectorCnt);
		/**
		 * 构造tab容器
		 */
		this.tabCnt = new dhtmlXTabBar(selectorCnt);
		this.tabCnt.setSkin('glassy_blue');
	  	this.tabCnt.setImagePath(Milan.skinType+"images/dhtmlx/");
		this.tabCnt.setTabContentZoneSize({width:"100%",height:this.config.height+"px"});
		this.tabCnt.getTabContentZone().style.overflow = "auto";
		
		this.recentCntId = "userSelector_recentItem";
		this.onlineUserCntId = "userSelector_onlineUserItem";
		this.orgSelectorCntId = "userSelector_orgItem";
		this.tabCnt.setTabActive(this.recentCntId);
		this.container.setPosition();
		if(!this.config.isRecentEnable)
		{
			this.tabCnt.addTab(this.orgSelectorCntId,this.config.orgTitle);
			this.tabCnt.setTabActive(this.orgSelectorCntId);
			this.loadOrgSelectUI(this.orgSelectorCntId);
			return ;
		}
		this.tabCnt.attachEvent("onSelect",function(id)
		{
			return this.lazyLoadTabContent(this,id);
		}.bind(this));
		this.tabCnt.addTab(this.recentCntId,"最近使用");
		if(this.config.isOnlineUser){
			this.tabCnt.addTab(this.onlineUserCntId,"在线用户");
		}
		this.tabCnt.addTab(this.orgSelectorCntId,this.config.orgTitle);
		this.tabCnt.setTabActive(this.recentCntId);
		
		this.loadRecentItemUI();
	},
	lazyLoadTabContent : function(target,idd)
	{
		if(idd==target.orgSelectorCntId&&(!target.orgSelectorLoaded))
		{
			target.loadOrgSelectUI(idd);
		}
		if(target.config.isOnlineUser && idd == target.onlineUserCntId && !target.onlineUserLoaded){
			target.loadOnlineUserUI(target,idd);
		}
		return true;
	},
	loadOnlineUserUI:function(target,idd){
		Milan.ajaxutility.formSubmit({
			method:"GET",
			url:"onLineMessageAction.do?actionType=15&isMulti="+target.isMulti,
			success:function(res){
				target.tabCnt.setContentHTML(idd,res.responseText);
				target.onlineUserLoaded=true;
				Milan.commonutils.checkBoxRelation("online_user_formid","checkall","OrgSelector_ChkItem");
				jQuery("#online_user_formid").find("#online_user_keyword1").keydown(function(evt){
					evt = evt || event;
					if (evt.keyCode==13){
						Milan.pagejs.page_index.onlineUserSearch(target);
					}else{
						target.keywordSearchCount = 0;
					}
				});
				jQuery("#online_user_searchBtn").click(function(){Milan.pagejs.page_index.onlineUserSearch(target)});
				target.showScrollBar();
			},
			displayLoading:false,
			displayMasker:false
		});
	},
	loadRecentItemUI : function()
	{
		var orgSelectorCnt = Milan.widget._createEle("DIV");
		orgSelectorCnt.className = "orgSelect-selectorCnt";
		orgSelectorCnt.appendChild(this.createListCnt(this.config.height-40));
		this.tabCnt.setContent(this.recentCntId,orgSelectorCnt);
		this.initItemList();
	},
	loadOrgSelectUI : function(idd)
	{
		var orgSelectorCnt = Milan.widget._createEle("DIV");
		orgSelectorCnt.className = "orgSelect-selectorCnt";
		var selectBar = Milan.widget._createEle("DIV");
		selectBar.className  = "orgSelect-selectBar";
		var deptSelector,keyInput=null,searchBtn;
		if (this.config.isDeptSelEnable) 
		{
			deptSelector = Milan.widget._createEle("SELECT");
			selectBar.appendChild(deptSelector);
			this.deptSelector = deptSelector;
			
			deptSelector.onchange = function()
			{	var key="";
				if(this.config.isSearchEnable&&keyInput!=null){
					key=keyInput;
				}
				this.itemSearch.call(this, key);
			}.bind(this);
		}
		
		if (this.config.isSearchEnable) 
		{
			keyInput = Milan.widget._createEle("INPUT");
			keyInput.className = "text-box";
			keyInput.type = "text";
			keyInput.name = "keyword";
			searchBtn = Milan.widget._createEle("A");
			searchBtn.className = "btn_short";
			searchBtn.href = "javascript:void(0)";
			searchBtn.innerHTML = "查询";
			selectBar.appendChild(document.createTextNode(" "));
			selectBar.appendChild(keyInput);
			selectBar.appendChild(document.createTextNode(" "));
			selectBar.appendChild(searchBtn);
			
			keyInput.onkeydown  = function(e)
			{
				var evnt = e||event;
				evnt.cancelBubble = true;
				if(evnt.keyCode == 13)
				{
					this.keyWordSearch(keyInput);
				}
			}.bind(this);
			searchBtn.onclick = function()
			{
				this.keyWordSearch(keyInput);
			}.bind(this);
		}
		
		orgSelectorCnt.appendChild(selectBar);
		orgSelectorCnt.appendChild(this.createListCnt(this.config.height-75));
		//orgSelectorCnt.appendChild(toolBar);
		orgSelectorCnt.onkeydown = function(e)
		{
			var ev = e||event;
			if(ev.keyCode == 13)
			{
				ev.returnValue = false;
			}
		}
		
		this.tabCnt.setContent(idd,orgSelectorCnt);
		
		this.orgSelectorLoaded = true;
		if (this.config.isDeptSelEnable) 
		{
			this.initOrgSelector();
		}
		Milan.domLoadingTimer(function()
		{
			this.itemSearch.call(this, "");
		}.bind(this), 10);
		//this.itemSearch("");
	},
	showScrollBar:function(){
		//ie6，ie7才需要执行以下代码
		if(Milan.navigator.isIE && parseInt(Milan.navigator.version.substring(0,1))<8){
			jQuery(".orgSelect-listCnt-list-cnt").each(function(){
				if(parseInt(this.scrollHeight) > parseInt(this.offsetHeight)){
					this.style.width="570px";
					this.style.overFlowY = "scroll"
			}});
		}
	},
	createListCnt : function(height)
	{
		var listCnt = Milan.widget._createEle("DIV");
		listCnt.className =  "orgSelect-listCnt";
		var listCnt2 = Milan.widget._createEle("DIV");
		listCnt2.className = "orgSelect-listCnt-list"
		var listCnt3 = Milan.widget._createEle("DIV");
		listCnt3.className = "orgSelect-listCnt-list-cnt";
		listCnt3.style.height = height + "px";
		listCnt.appendChild(listCnt2);
		listCnt2.appendChild(listCnt3);
		this.listCnt = this.orgSelectorListCnt = listCnt3;
		var toolBar = Milan.widget._createEle("DIV");
		toolBar.className = "orgSelect-toolBar";
		listCnt.appendChild(toolBar);
		return listCnt;
	},
	createCheckAllBtn : function(listCnt){
		var checkAllDiv = Milan.widget._createEle("DIV");
		checkAllDiv.style.styleFloat = "left";
		if (this.isMulti) 
		{
			if (this.config.supportCheckAll) 
			{

				var checkAllBtn = Milan.widget._createEle("input");
				checkAllBtn.type="checkbox";
				checkAllBtn.className="checkall";
				checkAllDiv.appendChild(checkAllBtn);
				this.checkAllBtn = checkAllBtn;
				checkAllBtn.onclick = function()
				{
					this.checkFun(checkAllBtn);
				}.bind(this);
			}
		}
		jQuery(listCnt).find("div#orgSelect-listCnt-header")[0].appendChild(checkAllDiv);
//		jQuery(orgSelectorCnt).find("div#orgSelect-listCnt-header")[0].appendChild(checkAllDiv);
	},
	createnCnt : function()
	{
		var _config={width : "600px",confirmCallback: function(){return this.onSelectedCallBack();}.bind(this),cancelCallback: function(){this.onCancelCallBack();}.bind(this)}
		if(this.config.isContainChildren){
			_config.thirdBtnTxt="确定（包含子部门）";
			_config.thirdBtnClass="btn_longest";
			_config.thirdBtnCallback=function(){return this.thirdBtnCallback();}.bind(this);
		}
		this.container =new Milan.widget.ConfirmDialog(this.config.title, "", _config); 
	},
	initOrgSelector : function()
	{
		var deptUrl =new Milan.commonutils.StringBuffer();
		deptUrl.append(this.config.deptUrl);
		deptUrl.append("&orgType=");
		deptUrl.append(this.config.orgType);
		Milan.ajaxutility.formSubmit({
			method:"GET",
			url:deptUrl.toString(),
			success:this.updateOrgSelectorCallBack.bind(this),
			displayLoading:false,
			displayMasker:false
		});
	},
	initItemList : function()
	{
		var quickSelectUrl = new Milan.commonutils.StringBuffer();
		quickSelectUrl.append(this.config.quickSelectUrl);
		quickSelectUrl.append("&orgType=");
		quickSelectUrl.append(this.config.orgType);
		//Milan.ajaxutility.getResult("GET",quickSelectUrl.toString(),this.updateItemListCallBack.bind(this),null,{displayLoading:false});
		Milan.ajaxutility.formSubmit({
			method:"GET",
			url:quickSelectUrl.toString(),
			success:function(response,option){
				this.updateItemListCallBack(response,option);//.bind(this);
				if(response&&response.responseText)
				{
					var data = eval("("+response.responseText+")");
					data = data.root;
					if(data.length == 0){
						this.tabCnt.setTabActive(this.orgSelectorCntId);
						this.lazyLoadTabContent(this, this.orgSelectorCntId);
					}
				}
			}.bind(this),
			displayLoading:false,
			displayMasker:false
		});		
	},
	itemSearch : function(key)
	{
		var keyValue;
		if(typeof key == "string")
			keyValue = key.trim();
		else
			keyValue = key.value.trim();
		
		var deptId = "";
		if(this.deptSelector)
			deptId = this.deptSelector.options[this.deptSelector.selectedIndex].value;
		
		deptId = deptId.split("|")[0];

		var searchUrl = new Milan.commonutils.StringBuffer();
		searchUrl.append(this.config.searchUrl);
		searchUrl.append("&keyid=");
		searchUrl.append(deptId);
		searchUrl.append("&orgType=");
		searchUrl.append(this.config.orgType);
		searchUrl.append("&key=");
		searchUrl.append(encodeURIComponent(keyValue));
		if(this.config.pageSize){
			searchUrl.append("&pageSize=");
			searchUrl.append(this.config.pageSize);
			searchUrl.append("&pageNo=1");
			//alert("searchUrl : " + searchUrl);
		}
		//Milan.ajaxutility.getResult("GET",searchUrl.toString(),this.updateItemListCallBack.bind(this),null,{displayLoading:false});
		
		jQuery(".orgSelect-listCnt-list-cnt").scrollTop(0);
		
		Milan.ajaxutility.formSubmit({
			method:"GET",
			url:searchUrl.toString(),
			success:this.updateItemListCallBack.bind(this),
			displayLoading:false,
			displayMasker:false
		});
	},
	keyWordSearch : function(key,pageNo)
	{
		var keyValue;
		if(typeof key == "string")
			keyValue = key.trim();
		else
			keyValue = key.value.trim();
		this.keyword = keyValue;
		var deptId = "";
		if(this.deptSelector)
			deptId = this.deptSelector.options[this.deptSelector.selectedIndex].value;
		deptId = deptId.split("|")[0];
		var searchUrl =new Milan.commonutils.StringBuffer();
		searchUrl.append(this.config.searchUrl);
		searchUrl.append("&key=");
		searchUrl.append(encodeURIComponent(keyValue));
		searchUrl.append("&orgType=");
		searchUrl.append(this.config.orgType);
		searchUrl.append("&keyid=");
		searchUrl.append(deptId);
		if(this.config.pageSize){
			searchUrl.append("&pageSize=");
			searchUrl.append(this.config.pageSize);
			if(pageNo){
				searchUrl.append("&pageNo=");
				searchUrl.append(pageNo);
				this.pageNo = pageNo;
			}else
				searchUrl.append("&pageNo=1");
			//alert("searchUrl : " + searchUrl);
		}
		//Milan.ajaxutility.getResult("GET",searchUrl.toString(),this.updateItemListCallBack.bind(this),null,{displayLoading:false});
		Milan.ajaxutility.formSubmit({
			method:"GET",
			url:searchUrl.toString(),
			success:this.updateItemListCallBack.bind(this)
		});
	}
	,
	nextPage : function(pageNo,formId)
	{
		this.formId = formId;
		var keyValue = this.keyword?this.keyword:"";
		var deptId = "";
		if(this.deptSelector)
			deptId = this.deptSelector.options[this.deptSelector.selectedIndex].value;
		deptId = deptId.split("|")[0];
		var searchUrl =new Milan.commonutils.StringBuffer();
		searchUrl.append(this.config.searchUrl);
		searchUrl.append("&key=");
		searchUrl.append(encodeURIComponent(keyValue));
		searchUrl.append("&orgType=");
		searchUrl.append(this.config.orgType);
		searchUrl.append("&deptId=");
		searchUrl.append(deptId);
		if(this.config.pageSize){
			searchUrl.append("&pageSize=");
			searchUrl.append(this.config.pageSize);
			if(pageNo){
				searchUrl.append("&pageNo=");
				searchUrl.append(pageNo);
				this.pageNo = pageNo;
			}else
				searchUrl.append("&pageNo=1");
			//alert("searchUrl : " + searchUrl);
		}
		//Milan.ajaxutility.getResult("GET",searchUrl.toString(),this.updateItemListCallBack.bind(this),null,{displayLoading:false});
		Milan.ajaxutility.formSubmit({
			method:"GET",
			url:searchUrl.toString(),
			success:this.appendNextPage.bind(this)
		});
	},
	appendNextPage : function(response,option)
	{
		if(response&&response.responseText)
		{
			var respObj = eval("("+response.responseText+")");
			data = respObj.root;
			var cache = [];
			var style ;
			for(var i=0,ilen3=data.length;i<ilen3;i++)
			{
				style = "orgSelect-listCnt-list-cnt-datagrid-tdbg1";
				if(i%2==0) style = "orgSelect-listCnt-list-cnt-datagrid-tdbg2";
				var tr  ="<tr class='"+style+"'>";
				var oBuffer=new Milan.commonutils.StringBuffer();
				oBuffer.append(tr);
				for(var j=0,jlen1=this.config.columnModel.columns.length;j<jlen1;j++)
				{
					if (j == 0) 
					{
						oBuffer.append("<td>");
						if(this.config.columnModel.columns[j].render)
							oBuffer.append(this.config.columnModel.columns[j].render(eval("data[i]." + this.config.columnModel.columns[j].dataIndex),data[i]));
						oBuffer.append(this.defaultIdColumnRender(eval("data[i]." + this.config.columnModel.columns[j].dataIndex), data[i]) + "</td>");
					}
					else
					{
						if(this.config.columnModel.columns[j].render)
						{
							oBuffer.append("<td>");
							oBuffer.append(this.config.columnModel.columns[j].render(eval("data[i]." + this.config.columnModel.columns[j].dataIndex),data[i]) );
							oBuffer.append("</td>");
						}
						else
						{
							oBuffer.append("<td>");
							oBuffer.append(this.defaultColumnRender(eval("data[i]." + this.config.columnModel.columns[j].dataIndex),data[i]));
							oBuffer.append("</td>");
						}
					}
				}
				oBuffer.append("</tr>");
				var sResult=oBuffer.toString();
				cache.push(sResult);
			}
			var rs = cache.join("");
			jQuery("#"+this.formId).find("tbody").append(rs);
			var totalPage = parseInt(respObj.totalRecords)/parseInt(this.config.pageSize);
			if(this.pageNo < totalPage)
				this.loading = false;
		}
		
	},
	back2QuickList : function()
	{
		this.initItemList();
	},
	updateOrgSelectorCallBack : function(response,option)
	{
		if(response&&response.responseText)
		{
			var data = eval("("+response.responseText+")");
			data = data.root;
			if(data)
			{
				for(var i=0,iilen=data.length;i<iilen;i++)
				{
					var o = Milan.widget._createEle("OPTION");
					o.text = this.getTreeEntry(data[i].name,data[i].orgInfo);
					var oBuffer=new Milan.commonutils.StringBuffer();
					oBuffer.append(data[i].id);
					oBuffer.append("|");
					oBuffer.append(data[i].parentDeptID);					
					o.value = oBuffer.toString();
					this.deptSelector.options.add(o);
				}
			}
		}
	},
	updateItemListCallBack : function(response,option)
	{
		this.loading = false;
		if(response&&response.responseText)
		{
			var data = eval("("+response.responseText+")");
			var totalRecords = data.totalRecords;
			data = data.root;
			if(this.callBackConfig.beforeListShowCallBack)this.callBackConfig.beforeListShowCallBack(data);
			var obj = this.createDataGrid(data);
			this.listCnt.innerHTML = obj.html;
			setTimeout(function(){jQuery("#"+obj.formId).find("input").blur();}.bind(obj),600);
			if(totalRecords < this.config.pageSize)
				this.loading = true;
			var selector = this;
			if(this.config.pageSize && !this.loading){
				jQuery("#"+obj.formId).parents(".orgSelect-listCnt-list-cnt").unbind('scroll');
				jQuery("#"+obj.formId).parents(".orgSelect-listCnt-list-cnt").scroll( function() {
					if(!selector.loading && this.scrollTop == (this.scrollHeight-this.offsetHeight)){
						//alert(this.scrollHeight + ":" + this.scrollTop);
						selector.loading = true;
						selector.nextPage(selector.pageNo?selector.pageNo+1:2,obj.formId);
					}
				});
			}
			if(!this.isMulti){
				jQuery("tr[class^='orgSelect-listCnt-list-cnt-datagrid-tdbg']").bind("click",function(){jQuery(this).find("input[type='radio']").attr("checked",true);});
			}else{
				this.createCheckAllBtn(this.listCnt);
				var form = null,itemLength = 0 , checkedItemLength = 0;
				jQuery("input[name='OrgSelector_ChkItem']").bind('click',function(){
						form = jQuery(this).parents("form");
						itemLength = form.find("input[name='OrgSelector_ChkItem']").length;
						if (itemLength==0) return;
						checkedItemLength = form.find("input:checked[name='OrgSelector_ChkItem']").length;	
						if(form.find(".checkall").length == 1)
							form.find(".checkall").attr("checked", (itemLength==checkedItemLength));
						
					});
			}
			if(this.callBackConfig.onListShowCallBack)this.callBackConfig.onListShowCallBack(data);
			
			if (this.callBackConfig && this.callBackConfig.itemCheckCallBack) 
			{
				var forms = document.getElementsByName("orgSelect-listCnt-list-cnt-datagrid-formname");
				if(forms)
				{
					for(var i=0,ilen1=forms.length;i<ilen1;i++)
					{
						forms[i].onclick = function(e)
						{
							var evnt = window.event || e;
							var target = evnt.target || evnt.srcElement;
							if (target.tagName.toUpperCase() == "INPUT"&&target.checked) 
								this.callBackConfig.itemCheckCallBack(target.value);
						}.bind(this);
					}
				}
				/*
				$("orgSelect-listCnt-list-cnt-datagrid-form").onclick = function(e)
				{
					var evnt = event || e;
					var target = evnt.target || evnt.srcElement;
					if (target.tagName.toUpperCase() == "INPUT"&&target.checked) 
						this.callBackConfig.itemCheckCallBack(target.value);
				}.bind(this);
				*/
			}
		}
		setTimeout(this.showScrollBar,10);
	},
	createDataGrid : function(data)
	{
		var cache = [];
		var style ;
		var randNum = Math.ceil((Math.random()*100));
		cache.push("<form id='orgSelect-listCnt-list-cnt-datagrid-formid_" + randNum + "' name='orgSelect-listCnt-list-cnt-datagrid-formname'><TABLE class='orgSelect-listCnt-list-cnt-datagrid'><tr>");
		for(var i=0,ilen2=this.config.columnModel.columns.length;i<ilen2;i++)
		{
			cache.push("<td class='orgSelect-listCnt-list-cnt-datagrid-title'");
			if(this.config.columnModel.columns[i].style){
				cache.push(" style='");
				cache.push(this.config.columnModel.columns[i].style);
				cache.push("'>");
			}else{
				cache.push(">");
			}
			
//			if(this.config.columnModel.columns[i].dataIndex=="id"){
//				cache.push("<td class='orgSelect-listCnt-list-cnt-datagrid-title' style='padding-left: 1px;'>");
//			}else{
//				cache.push("<td class='orgSelect-listCnt-list-cnt-datagrid-title'>");
//			}
			cache.push(this.config.columnModel.columns[i].header);
			cache.push("</td>");
		}
		cache.push("</tr>");
		if(data.length == 0){
			var oBuffer=new Milan.commonutils.StringBuffer();
			oBuffer.append("<tr class='orgSelect-listCnt-list-cnt-datagrid-tdbg2'>");
			oBuffer.append("<td align='center' colspan='");
			oBuffer.append(this.config.columnModel.columns.length);
			oBuffer.append("'>没有可用记录</td></tr>");
			cache.push(oBuffer.toString());
		}
		for(var i=0,ilen3=data.length;i<ilen3;i++)
		{
			style = "orgSelect-listCnt-list-cnt-datagrid-tdbg1";
			if(i%2==0) style = "orgSelect-listCnt-list-cnt-datagrid-tdbg2";
			var tr  ="<tr class='"+style+"'>";
			var oBuffer=new Milan.commonutils.StringBuffer();
			oBuffer.append(tr);
			for(var j=0,jlen1=this.config.columnModel.columns.length;j<jlen1;j++)
			{
				if (j == 0) 
				{
					oBuffer.append("<td>");
					if(this.config.columnModel.columns[j].render)
						oBuffer.append(this.config.columnModel.columns[j].render(eval("data[i]." + this.config.columnModel.columns[j].dataIndex),data[i]));
					oBuffer.append(this.defaultIdColumnRender(eval("data[i]." + this.config.columnModel.columns[j].dataIndex), data[i]) + "</td>");
				}
				else
				{
					if(this.config.columnModel.columns[j].render)
					{
						oBuffer.append("<td>");
						oBuffer.append(this.config.columnModel.columns[j].render(eval("data[i]." + this.config.columnModel.columns[j].dataIndex),data[i]) );
						oBuffer.append("</td>");
					}
					else
					{
						oBuffer.append("<td>");
						oBuffer.append(this.defaultColumnRender(eval("data[i]." + this.config.columnModel.columns[j].dataIndex),data[i]));
						oBuffer.append("</td>");
					}
				}
			}
			oBuffer.append("</tr>");
			var sResult=oBuffer.toString();
			cache.push(sResult);
		}
		cache.push("</table></form>");
		return {"html":cache.join(""),"formId":"orgSelect-listCnt-list-cnt-datagrid-formid_"+randNum};
	},
	getTreeEntry : function(deptName,deptPath)
	{
		var treeEntry = new Milan.commonutils.StringBuffer();
		var depth = deptPath.split("-").length;
		for(var i=1;i<depth;i++)
		{
			treeEntry.append("│");
		}
		treeEntry.append("├");
		treeEntry.append(deptName);
		return treeEntry.toString();
	},
	onSelectedCallBack : function()
	{
		var data = [];
		var orgInfoArray = [];
		var items = document.getElementsByName("OrgSelector_ChkItem");
		var isAnyCheck = false;
		if ((!items) || items.length < 1) 
		{
			Milan.commonutils.createDelayNotifyModel('提示信息', "没有选择任何选项");
			return isAnyCheck;
		}
		
		for(var i=0,ilen=items.length;i<ilen;i++)
		{
			if(items[i].checked == true&&Milan.commonutils.isShow(items[i].form))
			{
				isAnyCheck = true;
				var itemValues = eval("(" + items[i].value + ")");
				data.push(itemValues);
				orgInfoArray.push(items[i].value);
			}
		}
		if(!isAnyCheck)
		{
			Milan.commonutils.createDelayNotifyModel('提示信息', "没有选择任何选项");
			return isAnyCheck;
		}
		if (this.config.isUpdateRecentEnable) 
		{
			if (this.tabCnt.getActiveTab() == this.orgSelectorCntId) 
			{
				/*
				var updateRecentUrl = "userAction.do?actionType=56&orgType=" + this.config.orgType;
				var orgInfos = orgInfoArray.join("|");
				var params = new Milan.commonutils.StringBuffer();
				params.append("&orgInfos=");
				params.append(orgInfos);
				
				Milan.ajaxutility.formSubmit({
					url:updateRecentUrl,
					params:params.toString()
				});
				*/
				
			}
		}
		this.tabCnt.setTabActive(this.recentCntId);
		if(this.callBackConfig.onSelectedCallBack) return this.callBackConfig.onSelectedCallBack(data);
	},
	thirdBtnCallback:function(){
		if(this.callBackConfig.thirdBtnCallback){
			var data=[],oldSelectedCallBack=this.callBackConfig.onSelectedCallBack;
			this.callBackConfig.onSelectedCallBack=function(d){data=d;return true;};
			if(!this.onSelectedCallBack()){
				this.callBackConfig.onSelectedCallBack=oldSelectedCallBack;
				return false;
			}
			this.callBackConfig.onSelectedCallBack=oldSelectedCallBack;
			data.push({isContainChildren:true});
			return this.callBackConfig.thirdBtnCallback(data);
		}
	},
	onCancelCallBack : function()
	{
		if(this.callBackConfig.onCancelCallBack)this.callBackConfig.onCancelCallBack();
	},
	checkFun : function(checkAllBtn)
	{
		var items = jQuery(checkAllBtn).parents("form").find("input[name='OrgSelector_ChkItem']");
		if ((!items) || items.length < 1) return;
		if (checkAllBtn.checked) 
		{
			for (var i = 0,ilen5=items.length; i < ilen5; i++) 
			{
				if(!items[i].checked) items[i].click();
			}
//			checkAllBtn.innerHTML = "全不选";
		}
		else 
		{
			for (var i = 0,ilen6=items.length; i < ilen6; i++) 
			{
				items[i].checked = false;
			}
			
//			checkAllBtn.innerHTML = "全选";
		}
	},
	defaultIdColumnRender : function(cellData,rowData)
	{
		var selectionStr =new Milan.commonutils.StringBuffer();
		//因找不到办法将单引号传出，这里暂时将小写的单引号转义成大写的,如有需要使用时，必须先将大写转成小写
		if(this.isMulti)
		{
			selectionStr.append("<input type='checkbox' name='OrgSelector_ChkItem' value='");
			selectionStr.append(Object.toJSON(rowData).replace(/'/g,"＇") );
			selectionStr.append("'/>");
		
		}
		else{
			selectionStr.append("<input type='radio' name='OrgSelector_ChkItem' value='");
			selectionStr.append(Object.toJSON(rowData).replace(/'/g,"＇"));
			selectionStr.append("'/>");
		}
		return selectionStr.toString();
	},
	defaultColumnRender : function(cellData,rowData)
	{
		return cellData;
	}
}


/**
 * 部门单选器，将自动把选中的部门name和id,以及是否包含子部门等值赋给target
 * 
 * type 目前只能是D，代表是部门选择器
 * formId 查询表单ID
 * targetNameElement 保存所选部门Name的表单元素的名称
 * targetIdElement 保存所选部门ID的表单元素的名称
 * isShowChildBtun	是否显示包含子部门按钮
 * targetContainChildrenElement 保存是否包否子部门值的元素的名称
 */
 
Milan.widget.Selector.selectSingleDept = function(type, formId, targetNameElement, targetIdElement, isShowChildBtun, targetContainChildrenElement) {
    if (type.toUpperCase() == "D") 
	{
		var callBackFunction = {};//选中部门后的回调函数
		if (isShowChildBtun) {//根据是否显示包含子部门按钮传入不同回调函数
			callBackFunction = {
				onSelectedCallBack: function(arr){
					if (arr && arr.length > 0) {
						var form = $(formId);
						form[targetNameElement].value = arr[0].name;
						form[targetIdElement].value = arr[0].id;
					}
					form[targetContainChildrenElement].value = false;//不包含子部门
				},
				thirdBtnCallback: function(arr){
					if (arr && arr.length > 1) {
						var form = $(formId);
						form[targetNameElement].value = arr[0].name;
						form[targetIdElement].value = arr[0].id;
					}
					form[targetContainChildrenElement].value = true;//包含子部门
				}
			};
		}else{
			callBackFunction = {
				onSelectedCallBack: function(arr){
					if (arr && arr.length > 0) {
						var form = $(formId);
						form[targetNameElement].value = arr[0].name;
						form[targetIdElement].value = arr[0].id;
					}
				}
			};
		}
		new Milan.widget.Selector({
		orgType:"32",
		title:"选择部门",
		deptUrl:"departmentAction.do?actionType=20",
		quickSelectUrl:"departmentAction.do?actionType=22",
		searchUrl:"departmentAction.do?actionType=21&includeSelf=true",
		isContainChildren:isShowChildBtun?isShowChildBtun:false
		},
		false,callBackFunction);
	}
	else
			return;
}

